package com.starblink.android.basic.util

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.blankj.utilcode.util.ProcessUtils
import com.starblink.android.basic.bridge.BridgeCommand
import com.starblink.android.basic.bridge.BridgeUtil
import com.starblink.basic.util.CheckUtil
import com.starblink.basic.util.log.YYLogUtils


/**
 * 监听APP前后台状态切换
 * Created by dusensong on 2023/5/5.
 */
object AppStateTracker {
    const val STATE_FOREGROUND = 0
    const val STATE_BACKGROUND = 1
    var resumeActivityCount = 0 // 处于resume状态的Activity数量

    private var isAppLaunched = false //true表示APP已启动
    private var currentState = 0

    fun getCurrentState(): Int {
        return currentState
    }

    fun track(
        application: Application,
        appLaunch: (() -> Unit)? = null, //app启动时回调
        appTurnIntoForeground: (() -> Unit)? = null, //app进入前台时回调
        appTurnIntoBackGround: (() -> Unit)? = null, //app进入后台时回调
        appExist: (() -> Unit)? = null, //app退出时回调
    ) {
        application.registerActivityLifecycleCallbacks(object : SimpleActivityLifecycleCallbacks() {
            override fun onActivityStarted(activity: Activity) {
                //同步获取其它进程状态数量
                val processStr=BridgeUtil.getValueForKey(BridgeCommand.ValueKey.resumeActivityCount)
                var totalNum=resumeActivityCount
                if(!CheckUtil.isEmpty(processStr)){
                    totalNum+=processStr.toInt()
                }
                YYLogUtils.e("spm---> 进程 ${ProcessUtils.getCurrentProcessName()} --->onActivityStarted--->$totalNum")
                if (totalNum == 0) {
                    // APP进入前台
                    currentState = STATE_FOREGROUND

                    // 如果首次进入前台，即APP启动
                    if(!isAppLaunched&&BridgeUtil.isMainProcess()){
                        isAppLaunched = true
                        appLaunch?.invoke()
                    }else{
                        appTurnIntoForeground?.invoke()
                    }
                }
                resumeActivityCount++
            }

            override fun onActivityStopped(activity: Activity) {
                resumeActivityCount--
                //同步获取其它进程状态数量
                val processStr=BridgeUtil.getValueForKey(BridgeCommand.ValueKey.resumeActivityCount)
                var totalNum=resumeActivityCount
                if(!CheckUtil.isEmpty(processStr)){
                    totalNum+=processStr.toInt()
                }
                YYLogUtils.e("spm---> 进程 ${ProcessUtils.getCurrentProcessName()} --->onActivityStopped--->$totalNum")
                if (totalNum == 0) {
                    // APP进入后台
                    currentState = STATE_BACKGROUND
                    appTurnIntoBackGround?.invoke()
                }
            }
        })
    }


    private open class SimpleActivityLifecycleCallbacks : Application.ActivityLifecycleCallbacks {
        override fun onActivityCreated(activity: Activity, bundle: Bundle?) {}
        override fun onActivityStarted(activity: Activity) {}
        override fun onActivityResumed(activity: Activity) {}
        override fun onActivityPaused(activity: Activity) {}
        override fun onActivityStopped(activity: Activity) {}
        override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) {}
        override fun onActivityDestroyed(activity: Activity) {}
    }
}